package avicit.bdp.dds.server.worker.registry;

import avicit.bdp.common.utils.DateUtils;
import avicit.bdp.dds.common.Constants;
import avicit.bdp.dds.common.utils.OSUtils;
import avicit.bdp.dds.remote.utils.NamedThreadFactory;
import avicit.bdp.dds.server.registry.HeartBeatTask;
import avicit.bdp.dds.server.registry.ZookeeperRegistryCenter;
import avicit.bdp.dds.server.worker.config.WorkerConfig;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


/**
 *  worker registry
 */
@Service
public class WorkerRegistry {

    private final Logger logger = LoggerFactory.getLogger(WorkerRegistry.class);

    /**
     *  zookeeper registry center
     */
    @Autowired
    private ZookeeperRegistryCenter zookeeperRegistryCenter;

    /**
     *  worker config
     */
    @Autowired
    private WorkerConfig workerConfig;

    /**
     * heartbeat executor
     */
    private ScheduledExecutorService heartBeatExecutor;

    /**
     * worker start time
     */
    private String startTime;


    private Set<String> workerGroups;

    @PostConstruct
    public void init(){
        this.workerGroups = workerConfig.getWorkerGroups();
        this.startTime = DateUtils.dateToString(new Date());
        this.heartBeatExecutor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("HeartBeatExecutor"));
    }

    /**
     *  registry
     */
    public void registry() {
        String address = OSUtils.getHost();
        Set<String> workerZkPaths = getWorkerZkPaths();
        int workerHeartbeatInterval = workerConfig.getWorkerHeartbeatInterval();

        for (String workerZKPath : workerZkPaths) {
            zookeeperRegistryCenter.getZookeeperCachedOperator().persistEphemeral(workerZKPath, "");
            zookeeperRegistryCenter.getZookeeperCachedOperator().getZkClient().getConnectionStateListenable().addListener(new ConnectionStateListener() {
                @Override
                public void stateChanged(CuratorFramework client, ConnectionState newState) {
                    if (newState == ConnectionState.LOST) {
                        logger.error("worker : {} connection lost from zookeeper", address);
                    } else if (newState == ConnectionState.RECONNECTED) {
                        logger.info("worker : {} reconnected to zookeeper", address);
                        zookeeperRegistryCenter.getZookeeperCachedOperator().persistEphemeral(workerZKPath, "");
                    } else if (newState == ConnectionState.SUSPENDED) {
                        logger.warn("worker : {} connection SUSPENDED ", address);
                    }
                }
            });
            logger.info("worker node : {} registry to ZK {} successfully", address, workerZKPath);
        }

        HeartBeatTask heartBeatTask = new HeartBeatTask(this.startTime,
                this.workerConfig.getWorkerReservedMemory(),
                this.workerConfig.getWorkerMaxCpuloadAvg(),
                workerZkPaths,
                this.zookeeperRegistryCenter);

        this.heartBeatExecutor.scheduleAtFixedRate(heartBeatTask, workerHeartbeatInterval, workerHeartbeatInterval, TimeUnit.SECONDS);
        logger.info("worker node : {} heartbeat interval {} s", address, workerHeartbeatInterval);
    }

    /**
     *  remove registry info
     */
    public void unRegistry() {
        String address = getLocalAddress();
        Set<String> workerZkPaths = getWorkerZkPaths();
        for (String workerZkPath : workerZkPaths) {
            zookeeperRegistryCenter.getZookeeperCachedOperator().remove(workerZkPath);
            logger.info("worker node : {} unRegistry from ZK {}.", address, workerZkPath);
        }
        this.heartBeatExecutor.shutdownNow();
    }

    /**
     *  get worker path
     */
    private Set<String> getWorkerZkPaths() {
        Set<String> workerZkPaths = Sets.newHashSet();

        String address = getLocalAddress();
        String workerZkPathPrefix = this.zookeeperRegistryCenter.getWorkerPath();

        for (String workGroup : this.workerGroups) {
            StringBuilder workerZkPathBuilder = new StringBuilder(100);
            workerZkPathBuilder.append(workerZkPathPrefix).append(Constants.SLASH);
            if (StringUtils.isEmpty(workGroup)) {
                workGroup = Constants.DEFAULT_WORKER_GROUP;
            }
            // trim and lower case is need
            workerZkPathBuilder.append(workGroup.trim().toLowerCase()).append(Constants.SLASH);
            workerZkPathBuilder.append(address);
            workerZkPaths.add(workerZkPathBuilder.toString());
        }
        return workerZkPaths;
    }

    /**
     * get local address
     * @return local address
     */
    private String getLocalAddress(){
        return OSUtils.getHost() + Constants.COLON + workerConfig.getListenPort();
    }

}
